package com.canyou.listener;

import com.canyou.operlog.OpLogUtils;
import com.canyou.system.model.OperLog;
import com.canyou.system.service.OperLogService;
import com.canyou.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

/**
 * 操作日志时间监听器, 监听操作日志事件, 异步保存到数据库
 *
 * @author fy
 * @date 20/04/22 15:47
 */
@Slf4j
@Component
public class OpLogListener implements ApplicationListener<OpLogUtils.OpLogEvent> {

    @Autowired
    private OperLogService operLogService;

    @Async
    @Override
    public void onApplicationEvent(OpLogUtils.OpLogEvent event) {
        OperLog operLog = new OperLog();
        BeanUtils.copyProperties(event, operLog);
        operLog.setOperation((StringUtils.isNotBlank(event.getMainDataId()) ? event.getMainDataId() + "：" : "")
                + event.getOperateList().stream().collect(Collectors.joining("；")));
        operLogService.save(operLog);
    }

}
